package com.nash.demands;

import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class GoodsActivity extends ListActivity {

  public Vector<GoodsRowData> goods;
  private LayoutInflater mInflater;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Bundle b = getIntent().getExtras();
    // int addit = b.getInt("addit", 0);
    // long agentId = b.getLong("agent_id", 0);
    // String agentName = b.getString("agent_name");

    // vw1.setText("Name: " + name);
    // vw2.setText("State: " + String.valueOf(value));

    /*
     * String sql = "select " + BaseColumns._ID + ", " +
     * DemandsHelper.TBL_GOODS_ID_PARENT + "," + DemandsHelper.TBL_GOODS_NAME +
     * ", (select 1) from " + DemandsHelper.TBL_GOODS + " where " +
     * DemandsHelper.TBL_GOODS_IS_ARC + "=0 and id_parent=1 order by name";
     * Cursor data2 = DemandsActivity.db.rawQuery(sql, null); if
     * (data2.moveToFirst()) { do { goods.add(new
     * GoodsRowData(data2.getString(2), data2.getInt(0), data2.getInt(1), 1,
     * false, data2.getInt(3) > 0)); } while (data2.moveToNext());
     * 
     * } data2.close();
     */

    goods = new Vector<GoodsRowData>();
    final CustomAdapter adapter = new CustomAdapter(this, R.layout.goods_entry, R.id.name_entry, goods);
    this.setListAdapter(adapter);
    ListView lv = getListView();
    GoodsRowData gitem = new GoodsRowData("Все группы", 1, 0, 0, true, true);
    adapter.add(gitem);
    fetchLevel(adapter, gitem);

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
        Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putLong("id_goods", goods.get(pos).id);
        b.putString("goods_name", goods.get(pos).name);
        intent.putExtras(b);
        setResult(RESULT_OK, intent);
        finish();
        return true;
      }

    });

    lv.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        GoodsRowData gitem = goods.get(arg2);
        gitem.expanded = true;
        for (int i = 0, j = adapter.getCount(); i < j;) {
          GoodsRowData d = goods.get(i);
          if (d.level > gitem.level || (d.level == gitem.level && d != gitem)) {
            adapter.remove(d);
            j--;
          } else
            i++;
        }

        fetchLevel(adapter, gitem);
      }
    });
  }

  private void fetchLevel(final CustomAdapter adapter, GoodsRowData gitem) {
    String sql = "select " + BaseColumns._ID + ", " + Helper.TBL_GOODS_ID_PARENT + "," + Helper.TBL_GOODS_NAME +", (select count(*) from " + Helper.TBL_GOODS
        + " g2 where g2.id_parent=g1._id) from " + Helper.TBL_GOODS + " g1 where " + Helper.TBL_GOODS_IS_ARC + "=0 and id_parent=" + gitem.getId() + " order by name";
    Cursor data3 = DemandsActivity.db.rawQuery(sql, null);
    if (data3.moveToFirst()) {
      do {
        adapter.add(new GoodsRowData(data3.getString(2), data3.getInt(0), data3.getInt(1), gitem.level + 1, false, data3.getInt(3) > 0));
      } while (data3.moveToNext());

    }
    data3.close();
  }

  private class GoodsRowData {
    protected long id;
    protected int level;
    protected String name;
    protected boolean expanded;
    protected boolean expandable;

    public GoodsRowData(String pName, long pId, long pId_parent, int pLevel, boolean pExpanded, boolean pExpandable) {
      name = pName;
      id = pId;
      level = pLevel;
      expanded = pExpanded;
      expandable = pExpandable;
    }

    public long getId() {
      return id;
    }

    public String toString() {
      return name;
    }
  }

  private class CustomAdapter extends ArrayAdapter<GoodsRowData> {

    public CustomAdapter(Context context, int resource, int textViewResourceId, List<GoodsRowData> objects) {
      super(context, resource, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

      ViewHolder holder = null;

      TextView tvName = null;
      ImageView iv = null;

      GoodsRowData rowData = getItem(position);

      if (null == convertView) {
        convertView = mInflater.inflate(R.layout.goods_entry, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } //
      holder = (ViewHolder) convertView.getTag();
      tvName = holder.getName();
      tvName.setText(rowData.toString());

      iv = holder.getImage();
      if (rowData.expandable) {
        if (rowData.expanded)
          iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_list_goods_collapse));
        else
          iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_list_goods_expandable));
      } else {
        iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_list_goods_item));
      }
      return convertView;
    }
  }

  
  private class ViewHolder {
    private View mRow;
    private TextView tvName = null;
    private ImageView iv = null;

    protected ViewHolder(View row) {
      mRow = row;
    }

    protected TextView getName() {
      if (null == tvName) {
        tvName = (TextView) mRow.findViewById(R.id.name_entry);
      }
      return tvName;
    }

    protected ImageView getImage() {
      if (null == iv) {
        iv = (ImageView) mRow.findViewById(R.id.icon);
      }
      return iv;
    }
  }

}